0

I am writing a program for a bowling game and want to add 0 after every 10 in my array. e.g

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);

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

3

There are a few problems with your code.

  • You are accidentally using = 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.
  • You should be inserting the 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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.