I am writing a program for a bowling game and want to add 0 after every 10 in my array. eg
arr=[1,2,4,10,9,2,10,1,1];
this is what I want:
newarr=[1,2,4,10,0,9,2,10,0,1,1];
I have been trying:
for (i=0; i<arr.length; i++){
if (arr[i]=10){
newarr=arr.splice(i,0,0);
}
}
console.log(newarr);
By the way, you should use ==
for comparison.
var arr = [1, 2, 4, 10, 9, 2, 10, 1, 1]; var newArr = new Array(); for (i = 0; i < arr.length; i++) { newArr.push(arr[i]); if (arr[i] == 10) newArr.push(0); } alert(newArr);
There are a few problems with your code.
=
instead of ==
. The former is for assignment and the latter for comparison. Array.splice
modifies the original array, so there is no need for a new array. 0
at position i+1
instead of i
to add it after the 10
instead of before. arr=[1,2,4,10,9,2,10,1,1]; for (i=0; i<arr.length; i++){ if (arr[i]==10){ arr.splice(i+1,0,0); } } console.log(arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.