![](/img/trans.png)
[英]In ES5 Javascript, how do I add an item to an array and return the new array immediately, without using concat?
[英]How do I return a new length of the array in JavaScript
編寫一個名為 push 的 function,它接受兩個參數,一個數組和任何值。
function 應該將值添加到數組的末尾,然后返回數組的新長度。
不要使用內置的Array.push() function!
例子:
var arr = [1, 2, 3];
push(arr, 10); // 4
arr; // [1, 2, 3, 10]
我的問題是How to return a new array with the new length
。
你可以試試這個。 獲取現有數組的長度並將新數字放在它的 arr[length] 索引處。 請看下面的代碼:
function push(arr,num){
var length = arr.length;
arr[length]=num;
return arr;
}
你可以這樣做:
const push = (a, v) => (a[a.length] = v,a); array = [1,2,3] console.log(push(array, 4));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.