For loop with array unexpected identifier - javascript

I have two arrays which im checking against in a for loop, but am stuck on how to make the for loop work on the array.
The array is build like this in json_encode:
var bdata = {"1":["50","50","0","Player1"],"2":["1500","1000","1000","Player2"]};
The array i am comparing it against is encoded like this:
var vdata = {"uid":"1","total":"1","w":"1","t":"1","s":"1","g":"1","l":"0","upd":"0"};
Then i tried to create the loop by converting them into arrays but it does not work:
bdata = JSON.parse(bdata);
vdata = JSON.parse(vdata);
for(bdata[0] as bid){
if(vdata["w"] >= bdata[bid][1] && vdata["g"] >= bdata[bid][0] && vdata["s"] >= bdata[bid][2]){
document.getElementById(id).innerHTML += "<br/>"+bdata[bid][3];
}else{
document.getElementById(id).innerHTML += "<br/><font color='red'>"+bdata[bid][3]+"</font>";
}
}
But the error i get is : Unexpected identifier
I'm not even sure im looping the first array correctly ?

Plenty of syntax errors. For example
For loop syntax. Either use
for (init counter; condition; post loop operation)
eg,
for (var i = 0; i < array.length; i++)
or
for (property in collection)
Greater-than-or-equal-to comparison operator
>=
not
=>
You don't need to use JSON.parse(), you already have JSON objects

Related

How to put multiple objects in one array in javascript?

How to put multiple objects in one array in javascript?
I have n json strings like this:
first object
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"1"}]'
second object
'[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"2"}]'
third object
'[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"3"}]'
...
nth object
Here I want to put n obejects into one result
like this
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"1"},
[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"2"}],
[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"3"}]'
For this, I tried the following, but if I push it, it comes into the Array itself.
for (let i = 0; i < DataList.length; i++) {
if (i == 0) {
mergetData = JSON.parse(DataList[0]);
continue;
} else {
mergetData.push(JSON.parse(DataList[i]));
}
}
I am wondering how can I solve this problem.
Best Regards!
Parse all the JSON arrays, then concatenate them into a single array.
let parsedData = Datalist.map(s => JSON.parse(s));
let mergeData = [].concat(...parsedData);
Your are asking how to put multiple objects in one array but your desired output is the string object. So I'm considering your desired output as the actual question :)
For that you just have to iterate through your DataList and merge values into an string object.
StringObject = ''
for(let i=0; i < DataList.length; i++){
if(i===0)
StringObject += DataList[i]
else
StringObject += ',' + DataList[i]
}
console.log(StringObject)
Or just
StringObject = String(DataList)
console.log(StringObject)

Learning While Loops. Can't figure out what I am missing in my code.

Write a function called indexToString. This function should:
1. Take an array as an argument
2. Create and return a new array of all passed array elements as strings
3. Each strings should be formatted like so: “[index] is [element at index]”
This is the error I am getting: returns an array of passed-in array elements as strings with element index specified
expected undefined to deeply equal [ '0 is 1', '1 is 2', '2 is 3' ]
Here is my code:
var indexToString = function(array){
index = 0;
elementAtIndex = 0;
var i = 0;
while(i < array.length){
console.log(index + " is " + elementAtIndex);
i++
}
return array[i];
};
Two Three errors.
Firstly, the while loop will exit when i is no longer less than array.length; the first such number is array.length. This means, at the end of the loop, array[i] is array[array.length], which is just outside the array, thus undefined.
Secondly, you are supposed to return an array of strings, as told by your test failure message; not print them to the console.
EDIT: Thirdly, what Spencer said. :) Use i instead of index, and array[i] instead of elementAtIndex.
You want to start with an empty array outside the loop, and push each string you construct into it; then return that array after the loop.
Or you can do it with "new" JavaScript:
var indexToString = array => array.map((e, i) => `${i} is ${e}`)
You should reflect a bit more on your code, it is quite nonsense so far.
Let's decompose the question to identify what should be done:
Write a function called indexToString. This function should:
Take an array as an argument
Create and return a new array of all passed array elements as strings
Each strings should be formatted like so: “[index] is [element at index]”
So:
you create a function called indexToString which body contains the code, as you did.
In the initialization part before your while, you should create a new empty array that is going to be filled, and declare an integer called index for example initialized at 0 that is going to be used to loop through the original array. (Tip: var new_array = []; to create, and use new_array.push(elem); to append an element)
in your while, you should push at the end of your new array a string built as follow: "["+index+"] is ["+array[index]+"]" AND you should increment your index. You loop while(index < array.length).
At the end, you can return the new array !
Good luck with learning programming!
If the arraylenth is 10, the function will return array[10].This is an array-bound.
When you enter the last loop, the i becomes equal to array.length, so array[i] is undefined after this. But probably this is not what you wanted. you want to return the full array.
var indexToString = function(array){
var new_array = [];
var i = 0;
while(i < array.length){
new_array[i] = i + " is " + array[i];
i++;
}
return new_array;
};
console.log(indexToString([1,2,3]));

Array Says Its Length Is 0 But Console Says Otherwise

Good Afternoon,
I have encountered a problem with my code:
I have a for function adding values to an array variable but whenever I run the page it gives me an error stating that the array is empty. Here's the code adding values to the array:
if(this.Type === "Image") {
this.Frames = [];
for(var i = 0; i <= Sources.length - 1; i++) {
var Img = new Image();
Img.src = Sources[i];
this.Frames["Frame" = i] = Img;
}
} else {
this.Frames = [];
for(var i = 0; i <= Sources.length - 1; i++) {
this.Frames["Frame" + i] = Sources[i];
}
}
The code runs fine. How do I know that? Well I went on the JavaScript console and checked what value the array had. It said Frames[0], but when I collapsed it, it had Frame0, and when I collapsed that, the source it had was the correct source. So, what is going on with this? Is it a glitch or am I doing something wrong that I didn't know of before?
Thanks in advance.
That's because JavaScript only has numeric arrays. It does not have associative arrays.
When you do: this.Frames["Frame" + i] = Sources[i];, what you are doing is adding a property to the array (in JavaScript, everything is an object, and can therefore have properties). You are not actually pushing to the array.
One thing you can do is use an object instead: this.Frames = {};.
Or, you can .push() onto the array and use it as a numeric array.
this.Frames[i] = Sources[i];
// or
this.Frames.push(Sources[i]);
The .length property of JavaScript arrays only counts properties whose names are strings that look like integers (like "0", "1", etc). You can add whatever properties you want to an array instance, but only numeric properties affect the length of the array.

JavaScript Array

I usually script/program using python but have recently begun programming with JavaScript and have run into some problems while working with arrays.
In python, when I create an array and use for x in y I get this:
myarray = [5,4,3,2,1]
for x in myarray:
print x
and I get the expected output of:
5
4
3
..n
But my problem is that when using Javascript I get a different and completely unexpected (to me) result:
var world = [5,4,3,2,1]
for (var num in world) {
alert(num);
}
and I get the result:
0
1
2
..n
How can I get JavaScript to output num as the value in the array like python and why is this happening?
JavaScript and Python are different, and you do things in different ways between them.
In JavaScript, you really should (almost) always iterate over an array with a numeric index:
for (var i = 0; i < array.length; ++i)
alert(array[i]);
The "for ... in" construct in JavaScript gives you the keys of the object, not the values. It's tricky to use on an array because it operates on the array as an object, treating it no differently than any other sort of object. Thus, if the array object has additional properties — which is completely "legal" and not uncommon — your loop will pick those up in addition to the indexes of the "normal" array contents.
The variable num contains the array item's index, not the value. So you'd want:
alert(world[num])
to retrieve the value
The for var in... loop in JavaScript puts the keys in the variable instead of the actual value. So when using for var ... you should do something like this:
var world = [5, 4, 3, 2, 1];
for ( var key in world ) {
var value = world[key];
alert(key + " = " + value);
}
And note that this way of looping is best used when you're using objects instead of arrays. For arrays use the common:
for ( var i = 0, j = arr.length; i < j; i++ ) { ... }
Or if you're targeting modern browser you can use the forEach-method of arrays:
var arr = [1, 2, 3];
arr.forEach(function(num) {
alert(num);
});
The for...in loop loops over all key elements; not the values.
I would recommend you to use
for(var i=0; i<arr.length; i++){
alert(arr[i]);
}
When you use the in operator num becomes a key. So simply use this key to get a value out of the array.
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
try this.
var world = [5,4,3,2,1]
for(var i=0;i<world.length;i++){
alert(world[i])
}
Because javascript in your case is printing the index of the element, not the value.
the result you got is just element index,if you want to get element value
your code should like this
var world = [5,4,3,2,1]
for (var num in world) {
alert(world[num]);
}
The for in iteration in JavaScript works only for the object data type. The way it works is that it lets you iterate over the attributes of an object. arrays are objects in JavaScript, but the for in only works on its attributes, not the array values.
For example you might define an array as such:
var arr = [1,2,3];
And you can assign attributes to this array, because it's actually an object:
arr.foo = "bar";
arr["1"] = 2;
Now when you use the for in iteration method you will be able to iterate over the attributes we just assigned above;
for(var i in arr) console.log(i);
To iterate over the actual array values you need to use the for(var i=0; i<arr.length; i++) construct.
Hope this helps.
In javascript it's advised to loop Arrays different from looping Objects. You are using an object loop, which may return unexpected result (for instance if the Array.prototype was extended with custom methods you would iterate those too, and it does't guarantee the order of the array is preserved). There are many ways to loop through an array, using it's index:
// regular
var arr = [1,2,3,4,5]
,i
;
for (i=0;i<arr.length;i++) {
console.log(arr[i]);
}
// using while
var arr = [1,2,3,4,5]
,i = 0
;
while ((i = i + 1)<arr.length) {
console.log(arr[i]);
}
// using while reversed
var arr = [1,2,3,4,5]
,i = arr.length
;
while ((i = i - 1) > -1) {
console.log(arr[i]);
}
Note: Why not use i++ or i--? To avoid confusion, index out of range-errors and to satisfy JSLint

How to better iterate over a huge array with lots of undefined items

Consider the following code:
var _test1 = [];
_test1[88] = 'sex';
_test1[1999990] = 'hey';
for(i = 0, length = _test1.length; i < length; i++){
if(_test1[i] == 'hey'){
alert(_test1.length);
}
}
this takes a lot of time, and there are only 2 values.
Is there any way to be faster? Even by using another system that index objects by a number and then loop them fast?
You can use a for / in loop:
for (var i in _test1) {
if (!_test1.hasOwnProperty(i) || isNaN(+i)) continue;
if(_test1[i] == 'hey'){
alert(_test1.length);
}
}
This is exactly what you're looking for; it will only loop over the indices that are actually defined, and will skip any holes in the array.
Have you tried using an Object instead? Numbers should be converted to strings automatically. You would traverse the list with a for...in loop.

Categories