简体   繁体   English

将一个空元素推入javascript数组

[英]Push an empty element into javascript array

How can I push empty element to an existing Js array, lets assume :如何将空元素推送到现有的 Js 数组,让我们假设:

 var arr = [54,77,21]; var target = [54,77,21,,,,36]; arr.push(); //do not append an empty element into the array. arr.push(); console.log(JSON.stringify(arr)); //output: [54,77,21]

How to append empty elements so "arr" will be equivalent to "target" array?如何附加空元素使“arr”等同于“target”数组?

You could address the index directly.您可以直接寻址索引。 This builds a sparse array.这将构建一个稀疏数组。

 var arr = [54,77,21]; arr[6] = 36; console.log(JSON.stringify(arr));

Or push undefined until you like to push the value.或者推送undefined直到你想推送值。 This returns a filled array.这将返回一个填充数组。

 var arr = [54,77,21]; arr.push(undefined); arr.push(undefined); arr.push(undefined); arr.push(36); console.log(JSON.stringify(arr));

By using JSON.stringify , you get for undefined or sparse items null , because JSON knows only null instead of undefined .通过使用JSON.stringify ,您会得到 undefined 或稀疏项null ,因为JSON只知道null而不是undefined

You can use Array#length :您可以使用Array#length

arr.length++;

You can set the length property to truncate an array at any time.您可以随时设置 length 属性来截断数组。 When you extend an array by changing its length property, the number of actual elements increases ;当您通过更改长度属性来扩展数组时,实际元素的数量会增加 for example, if you set length to 3 when it is currently 2, the array now contains 3 elements, which causes the third element to be a non-iterable empty slot.例如,如果在当前为 2 时将 length 设置为 3,则数组现在包含 3 个元素,这会导致第三个元素成为不可迭代的空槽。

But note that JSON does not support sparse arrays.但请注意,JSON 不支持稀疏数组。 Ie you cannot see empty slots with JSON.stringify .即你看不到JSON.stringify空槽。

 var arr = [54,77,21]; arr.length++; arr.length++; arr.length++; arr.push(36); console.log(arr);

(FYI: Stack Snippets do not seem to support sparse arrays correctly. You need to run that code in the browser console instead.) (仅供参考:Stack Snippets 似乎不正确支持稀疏数组。您需要在浏览器控制台中运行该代码。)

You could use the array.prototype.concat() method.您可以使用array.prototype.concat()方法。

 var arr1 = [1, 2, 3, 4]; var arrtarget = [1, 2, 3, 4, , , , 5, 6]; console.log(arr1); console.log(arrtarget); newArr = arr1.concat([, , , 5,6]); console.log(newArr);

Alternatively, you could use the Array.Prototype.push() method as或者,您可以使用Array.Prototype.push()方法作为

arr1.push(undefined);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM