I'm learning about arrays in Code.org.
So there are methods like insertItem(list, index, item) in code.org, but as I read many books about arrays in javaScript, none of them talked about the insertItem Method.
I wanted to know if insertItem is generic to JS or is it just specifically made for the code.org platform?
-
sounds like a functionMiroslav Glamuzina– Miroslav Glamuzina2019年03月05日 03:44:35 +00:00Commented Mar 5, 2019 at 3:44
4 Answers 4
That method is only on code.org https://docs.code.org/applab/insertItem/
But JS has a similar method you can use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Comments
insertItem() is purely code.org
https://docs.code.org/applab/insertItem/
To do this in regular javascript, you would:
- If you wanted to insert the item into the end of the array, you would use
.push()
var array = [0, 1, 2];
console.log(array);
array.push("item");
console.log(array);
- If you wanted to replace an item in the array (in which you know the index), you would use
array[index] = item;
var array = [0, 1, 2];
console.log(array);
array[1] = "item";
console.log(array);
- If you wanted to replace an item in an array by knowing the value, but not the index, you would use
array[array.indexOf(value)] = item;
var array = [0, 1, 2];
console.log(array);
array[array.indexOf(1)] = "item";
console.log(array);
- Finally, if you wanted to insert an item into the array, you would use
.splice(). To insert an item after index 2, you would usearray.splice(2, 0, item).
var array = [0, 1, 2];
console.log(array);
array.splice(1, 0, "item");
console.log(array);
Code.org probably uses the following function to make life easier for you:
var array = [0, 1, 2];
function insertItem(list, index, item) {
list.splice(index, 0, item);
return list;
}
console.log(array);
array = insertItem(array, 1, "item");
console.log(array);
Comments
There is no method by name insertItem for Array in javascript. Also it seems insertItem(list, index, item) is a function and it accepts three arguments.
You can get list of javascript array methods in this link
Comments
There's no JavaScript function named insertItem - however, there's an almost identical method named splice - syntax like list.splice(index, 0, item):
var list = [1, 2, 4];
var item = 3;
var index = 2;
list.splice(index, 0, item);
console.log(list);