admin管理员组文章数量:1203179
How can I push empty element to an existing Js array, lets assume :
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 can I push empty element to an existing Js array, lets assume :
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?
Share Improve this question asked Jul 25, 2019 at 8:00 Voice Of The RainVoice Of The Rain 5871 gold badge12 silver badges31 bronze badges 4 |3 Answers
Reset to default 9You 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. 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
.
You can use Array#length
:
arr.length++;
You can set the length property to truncate an array at any time. 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.
But note that JSON does not support sparse arrays. I.e. you cannot see empty slots with 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.)
You could use the array.prototype.concat() method.
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
arr1.push(undefined);
本文标签: Push an empty element into javascript arrayStack Overflow
版权声明:本文标题:Push an empty element into javascript array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738578876a2101041.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
{0:54, 1: 77, 2: 21, 6: 36}
? – Justinas Commented Jul 25, 2019 at 8:04