如何在JavaScript中将对象(如字符串或数字)附加到数组中?
当前回答
我认为值得一提的是,push可以用多个参数调用,这些参数将按顺序附加到数组中。例如:
var arr=['first'];arr.push('第二个','第三个');控制台日志(arr);
因此,您可以使用push.apply将一个数组附加到另一个数组,如下所示:
var arr=['first'];arr.push('第二个','第三个');arr.push.apply(arr,['forth','fifth']);控制台日志(arr);
带注释的ES5提供了更多关于推送和应用功能的信息。
2016年更新:使用spread,您不再需要应用,例如:
var arr=['first'];arr.push('第二个','第三个');arr.push(…['furth','fifth']);控制台日志(arr);
其他回答
如果要附加两个数组-
var a = ['a', 'b'];
var b = ['c', 'd'];
那么您可以使用:
var c = a.concat(b);
如果您想将记录g添加到数组(var a=[]),那么可以使用:
a.push('g');
您可以使用JavaScript Spread运算符语法:
// Initialize the array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
使用凹面:
a=[1,2,3];b=[3,4,5];a=混凝土(b);控制台日志(a);
附加单个元素
// Append to the end
arrName.push('newName1');
// Prepend to the start
arrName.unshift('newName1');
// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';
附加多个元素
// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
附加一个数组
// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array
当然,concat()也可以用于二维数组。无需循环。
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何确定一个数组是否包含另一个数组的所有元素
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?
- JavaScript: override alert()
- 重置setTimeout