I am currently trying to figure out how to design some sort of loop to insert data into an array sequentially. I'm using Javascript in the Unity3D engine.
Basically, I want to store a bunch of coordinate locations in an array. Whenever the user clicks the screen, my script will grab the coordinate location. The problem is, I'm unsure about how to insert this into an array.
How would I check the array's index to make sure if array[0] is taken, then use array[1]? Maybe some sort of For loop or counter?
Thanks
To just add onto the end of an array, just use .push().
var myArray = [];
var coord1 = [12,59];
var coord2 = [87,23];
myArray.push(coord1);
myArray.push(coord2);
myArray, now contains two items (each which is an array of two coordinates).
Now, you wouldn't do it this way if you were just statically declaring everything as I've done here (you could just statically declare the whole array), but I just whipped up this sample to show you how push works to add an item onto the end of an array.
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push for some reference doc on push.
In case you need to know the array's length when reading the array in the future, you can use the .length attribute.
var lengthOfArray = myArray.length;
Using the .push() method as suggested by jfriend00 is my recommendation too, but to answer your question about how to work out what the next index is you can use the array's length property. Because JavaScript arrays are zero-based The length property will return an integer one higher than the current highest index, so length will also be the index value to use if you want to add another item at the end:
anArray[anArray.length] = someValue; // add to end of array
To get the last element in the array you of course say anArray[anArray.length-1].
Note that for most purposes length will give the number of elements in the array, but I said "one higher than the current highest index" above because JavaScript arrays are quite happy for you to skip indexes:
var myArray = [];
myArray[0] = "something";
myArray[1] = "something else";
myArray[50] = "something else again";
alert(myArray.length); // gives '51'
// accessing any unused indexes will return undefined
Related
Hi i am struggling to get my array in Pinescript to produce anything other than a list of Nan. I am trying to create an array of the % difference of the low and 20sma when price bounces off the 20sma but currently when i print the array it only has Nan values.
sma_20 = sma(close,20)
sma_20_touch_band = open>sma_20 and low<=sma_20
sma_20_dif = ((low-sma_20)/sma_20)
sma_20_array = array.new_float(100)
if sma_20_touch_band
array.push(sma_20_array, sma_20_dif)
array.shift(sma_20_array)
That is most likely caused by not using a var array. Without the var keyword, your array will be re-initialized on each bar. You need to initialze your array once, and manipulate its elements later on. Therefore make it:
var sma_20_array = array.new_float(100)
Also, I'm not so sure about your usage of the array.shift() function.
You push something to the array, but with the array.shift() you remove the first element from the array. At the end of the day, you remove what you have just added. At least this is what I think is happening.
As part of my nightwatchjs testing script, I have a 'dynamic' array that I would like to add a character to.
So, at the moment my array has a value of 4000, but I would like this to read 4,000.
This means that I need to add a , to my array.
The issue I have however, is that this value could change the next time I run the test script, so it could be 10000 or 100000.
So I suppose what I'm asking is whether it's possible to "select a value 3 elements from the end of my array?"
So no matter what or how many elements are in the array, the array will read xx,000.
Any help would be much appreciated. Many thanks.
Does this array have a single value? If so, why is it an array instead of just a variable?
You can use toLocaleString() to add commas to a numeric value, but it will return a string and not a number.
let arr = [4000]
let num = arr[0]
let commas = num.toLocaleString()
console.log(commas)
// "4,000"
I have a small problem. I created a large array.
It looks like this:
var Array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
If we write this way: Array[0] that shows all the elements.
If we write this way: Array[0][0] that shows "text1".
If we write this way: Array[0][2] that shows
-2 elements
-- 0: "text01"
-- 1: "text02"
.
If we write this way: Array[0][2].count or Array[0][2][0] it will not work
How do I choose each item, I need these elements for the tableView
The problem basically is that your inner array is illegal. Swift arrays must consist of elements of a single type. You have two types of element, String and Array Of String. Swift tries to compensate but the result is that double indexing can’t work, not least because there is no way to know whether a particular element will have a String or an Array in it.
The solution is to rearchitect completely. If your array entries all consist of the same pattern String plus String plus Array of String, then the pattern tells you what to do; that should be a custom struct, not an array at all.
as #matt already answered but I want to add this thing
Why Array[0][2].count or Array[0][2][0] not work
If you Define array
var array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
And when you type array you can see it's type is [[Any]] However it contains String as well as Array
So When you try to get Array[0][2] Swift does not know that your array at position 2 has another array which can have count
EDIT
What you are asking now is Array of dictionary I suggest you to go with model i.e create struct or class and use it instead of dictionary
Now If you want to create dictionary then
var arrOfDict = ["text10" : ["text01", "text02"] , "text11" : ["text11", "text12"]]
And you can access with key name let arrayatZero = arrOfDict["text10"] as? [String]
I am having the following problem with App Script in Google Sheet.
I want to make different copies of a row in my sheet base on a table. I want to do something like
input1=[[1,2,"a"]];
input2=[[4,5,"b"],[7,8,"c"]];
function (input1,input2) {
\\ input# is a row, ie. an array with single element, which is another array
\\ The rows input# represent are of equal length
out=[];
copy1=input1[0];//copy1 is a reference to input1[0]
copy2=input1[0];//copy2 is a reference to input1[0]
for (i=0;i<input1.length,i++) {//input1.length is 1
copy1[i]+=input2[0][i];
copy2[i]+=input2[1][i];
}
out.push(copy1,copy2);//copy1=[5,2,a] copy2=[8,2,a]
return out
}
I would expect out to look like
out=[[5,7,"ab"],[8,10,"ac"]];//[[5,2,a],[8,2,a]]
But it doesn't. The output looks like whenever I modified copy1 or copy2, it was input1 itself that was modified.
What is wrong here? How can I create a new array variable, assign its value as equal to an existing array and modify the new array without changing the old? Is it ok to have input arrays that whose elements (of elements) consist of mixed numeric and strings?
Using Slice() to return a copy of an Array
Try it this way:
function myFunction(input1,input2)
{
var input1=[[1,2,"a"]];
var input2=[[4,5,"b"],[7,8,"c"]];
var out=[];
var copy1=input1[0].slice();//slice returns a copy of the array
var copy2=input1[0].slice();
for (var i=0;i<input1[0].length;i++)//looping through all of elements of input1[0];
{
copy1[i]+=input2[0][i];
copy2[i]+=input2[1][i];
}
out.push(copy1,copy2);
Logger.log(out);//out=[[5,7,"ab"],[8,10,"ac"]];
}
For more information on slice look here.
This is a good question. I've struggled with it a few times myself.
How does one alter self in an Array to be a totally new array? How do I fill in the commented portion below?
class Array
def change_self
#make this array be `[5,5,5]`
end
end
I understand this: Why can't I change the value of self? and know I can't just assign self to a new object. When I do:
arr = [1,2,3,4,5]
arr contains a reference to an Array object. I can add a method to Array class that alters an array, something like:
self[0] = 100
but is it possible to change the length of the array referenced by arr?
How are these values stored in the Array object?
You are asking three very different questions in your title and in your text:
Is it possible to alter an Array object's length using an Array method?
Yes, there are 20 methods which can (potentially) change the length of an Array:
<< increases the length by 1
[]= can alter the length arbitrarily, depending on arguments
clear sets the length to 0
compact! can decrease the length, depending on contents
concat can increase the length, depending on arguments
delete can decrease the length, depending on arguments and contents
delete_at can decrease the length, depending on arguments
delete_if / reject! can decrease the length, depending on arguments and contents
fill can increase the length, depending on arguments
insert increases the length
keep_if / select! can decrease the length, depending on arguments and contents
pop decreases the length
push increases the length
replace can alter the length arbitrarily, depending on arguments and contents (it simply replaces the Array completely with a different Array)
shift decreases the length
slice! decreases the length
uniq! can decrease the length, depending on contents
unshift increases the length
When monkey patching the Array class, how does one alter "self" to be a totally new array? How do I fill in the commented portion below?
class Array
def change_self
#make this array be [5,5,5] no matter what
end
end
class Array
def change_self
replace([5, 5, 5])
end
end
How are these values actually stored in the Array object?
We don't know. The Ruby Language Specification does not prescribe any particular storage mechanism or implementation strategy. Implementors are free to implement Arrays any way they like, as long as they obey the contracts of the Array methods.
As an example, here's the Array implementation in Rubinius, which I find fairly readable (at least more so than YARV):
vm/builtin/array.cpp: certain core methods and data structures
kernel/bootstrap/array.rb: a minimal implementation for bootstrapping the Rubinius kernel
kernel/common/array.rb: the bulk of the implementation
For comparison, here is Topaz's implementation:
lib-topaz/array.rb
And JRuby:
core/src/main/java/org/jruby/RubyArray.java
arr = [1,2,3,4,5]
arr.replace([5,5,5])
I wouldn't monkey-patch a new method into Array; especially since it already exists. Array#replace
As Array are mutables, you can alter it's contents:
class Array
def change_self
self.clear
self.concat [5, 5, 5]
end
end
You modify the array so it becomes empty, and then add all the elements from the target array. They still are two different objects (ie, myAry.object_id would differ from [5, 5, 5].object_id), but now they are equivalent arrays.
Moreover, the array still is the same that before - just it's content changed:
myAry = [1, 2, 3]
otherRef = myAry
previousId = myAry.object_id
previousHash = myAry.hash
myAry.change_self
puts "myAry is now #{myAry}"
puts "Hash changed from #{previousHash} to #{myAry.hash}"
puts "ID #{previousId} remained as #{myAry.object_id}, as it's still the same instance"
puts "otherRef points to the same instance - it shows the changes, too: #{otherRef}"
Anyway, I really don't know why one would want to do this - are you solving the right problem, or just kidding with the language?