Home >Web Front-end >JS Tutorial >How to add an array to an object in js

How to add an array to an object in js

亚连
亚连Original
2018-06-19 16:34:3912868browse

Below I will share with you a js method to add array elements to an object in the simplest way. It has a good reference value and I hope it will be helpful to everyone.

As shown below:

//如题,通常做法就是循环数组,最后在添加length属性,如:

 
var obj = {}; 
 var pushArr = [11,22,33,44,55,66];
 for(var i=0;i<pushArr.length;i++) {
  obj[i] = pushArr[i];
 }
 obj.length = pushArr.length;

 console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}

Easy method:

//js将数组元素添加到对象中(或 数组转换成对象)有个小技巧:

var obj = {}; 
[].push.apply(obj,[11,22,33,44,55,66]);

console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}

由于obj是个对象没有像数组的push()方法,所以利用数组的push()以及apply()的特性来将数组作用于push()并修改当前的引用。 有较严重的代码洁癖的患者可以使用这个方法。

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to build Electron applications in Webpack

##Issues about unsafe image paths using Angular4

How to implement the cross coordinate following mouse effect in JS

How to use the EasyUI window in jQuery

How to use laydate.js date plug-in in Angular4.0

How to implement label scrolling switching in JS

How to implement pictures in JS Centered suspension effect

Questions about webpack3 speed-up optimization in vue-cli

How to implement a collapsible tree in Vue.js Shape menu

The above is the detailed content of How to add an array to an object in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn