For loop not giving proper result - javascript

var integer = 10;
var plus = [];
for(var i = 2; i < integer; i++) {
if(integer % i === 0){
plus.push[i];
}
}
console.log(plus)
this prints empty array, but why? shoudnt it print [2, 5]? I cant find what is wrong in my code

this works :
var integer = 10;
var plus = [];
for (var i = 2; i < integer; i++) {
if (integer % i === 0) {
plus.push(i);
}
}
console.log(plus)
so, basically what you were doing wrong is using .push[i]. its a common syntax error. you just need to use .push(i)

plus.push(i); instead of using plus.push[i];

Functions are objects in JavaScript. plus.push[i]; looks up a property on push, the function object, using i's value as the name (exactly like indexing into an array); and then throws away whatever value it got (presumably undefined, as the function probably doesn't have properties named "2", "4", etc.). That's why you're not getting a syntax error, as you would in many other languages.
To call push, use (), not []:
plus.push(i);

Related

(js) how to simultaneously iterate through an object while iterating through values

I am basically trying to get this problem to work and have isolated the issue to line 21. I think the way I'm trying to access the object key is wrong. I am simply trying to say: if the object key in the new object exists in the original array, push the new value from the new object into the new array.
Edit to add code block
function valueReplace(array, obj) {
var replaced = [];
for (var i = 0; i < array.length; i += 1) {
var value = obj[array[i]];
if (array.indexOf(obj.i) !== -1) {
replaced.push(value);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
You have a mixed up error report, but at the actual code, you try to access the object with the property i, obj.i, which not exists. Read more about property accessor.
For getting the wanted result, you might use the in operator for checking if a property in an object exists.
if (array[i] in obj) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
It looks like one of the issues you are having is trying to access a dynamic property with dot notation, which JS generally doesn't like. I reversed your logical if because IMO it makes more sense to see if the object has a property than get a property and then get the index of the array, but you could reverse it back to using index of by array.indexOf(obj[i]) !== -1
function valueReplace(array, obj) {
let replaced = [];
for (let i = 0, len = array.length; i < len; i++) {
if (obj.hasOwnProperty(array[i])) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
Because I generally like simplifying things here is this functionality rewritten in ES6 compatible code, using array.prototype.map. Don't use it for your homework, but if you want you can work it backwards into a standard function ;).
const valueReplace = (array, obj) => array.map(val => (obj.hasOwnProperty(val)) ? obj[val] : val);

Javascript global variable getting set to a new value [duplicate]

This question already has answers here:
Change the value of an array changes original array JavaScript
(3 answers)
Closed 7 years ago.
I'm new to javascript and coding in general, and I could use some help.
I am setting a global variable (generatedNumbers) equal to another variable (numbers) so that I can do some validation on the array. However, when I change the value of numbers, my global variable generatedNumbers gets changed as well. Any help would be appreciated.
var generatedNumbers;
function generateNumbers(numberOfNumbers) {
'use strict';
var i;
generatedNumbers = [];
for (i = 0; i < numberOfNumbers; i = i + 1) {
generatedNumbers.push(generateRandomNumber(9).toString());
}
}
function checkEachValidNumberUsed(userExpression, numbers) {
'use strict';
var i, j;
for (i = 0; i < userExpression.length; i = i + 1) {
for (j = 0; j < numbers.length; j = j + 1) {
if (userExpression[i] === numbers[j]) {
numbers.splice(j, 1);
window.console.log(generatedNumbers);
}
}
}
if (numbers.length !== 0) {
return true;
}
}
function validateExpression(userExpression) {
'use strict';
var numbers, validUserInput;
numbers = generatedNumbers;
window.console.log(generatedNumbers);
if (checkEachValidNumberUsed(userExpression, numbers)) {
document.getElementById("feedbackText").innerHTML = "Each number must be used exactly once.";
} else {
return true;
}
Arrays (and all other non-primitive types) are pass-by-reference, not copied, when you use the assignment operator = or pass them to a function, so any changes made to numbers (or the values of the elements of numbers) will be reflected in generatedNumbers.
For your array here, numbers = generatedNumbers.slice(0); will sufficiently clone the array, but keep in mind that if the contents of the array is not a primitive type (e.g. any object that you use the new keyword to create) will not be cloned: both arrays will reference the same objects.
That's because they both refer to the same object. If you want to make a copy of generatedNumbers (which I think you want to do in validateExpression) use slice.
numbers = generatedNumbers.slice(0);
In Javascript if you have an array
var a = [1,2,3,4];
and assign a to another variable
var b = a;
the two are referring the very same array object... for example after
b.push(99);
a will also see the mutated array.
If you want to make a copy you need to do so explicitly for example with
var b = a.slice();

Self Invoking Function returns "undefined"

Im trying to get a sum of array injected into a function that loops until all the values are added, the console.log right before the "return" logs the right value, meaning the code works, but when I try to use that function with any array it returns "undefined"...
var total = function(arr) {
console.log(arr);
if(arr.length > 1) {
var temp = []
for(var i=0, len=arr.length-1; i<len; i++) {
temp.push(arr[i] + arr[i+1]);
}
total(temp);
}
else {
console.log(arr.join()); // 48, exectly what I need
return parseInt(arr.join());
}
}
var sup = total([1,2,3,4,5]); // undefined
Not completely sure how to debug it..
If your arr.length is greater than one, you will invoke total with the temporary array, however, you don't do anything with this temporary array - you don't return it, or utilize it in any way, so the intermediate results are lost.
In addition - this is not a self invoking function; it is recursion.

How to change this in object?

How to create method twice? I can't understand how to change this in body of function. Why it doesn't work?
function twice() {
var buf = [];
for ( var i = 0; i < this.length; i++ ) {
buf.push(this[i]);
}
for ( var i = 0; i < this.length; i++ ) {
buf.push(this[i]);
}
this = buf;
}
Array.prototype.twice = twice;
a = [1,2,3];
a.twice();
a; // [1,2,3,1,2,3]
I can't understand how to change this in body of function
If you mean the value of this, you can't. But you don't have to for what you're doing
You're very close, you just have a fair bit to remove:
function twice() {
var i, l;
for (l = this.length, i = 0; i < l; ++i) {
this.push(this[i]);
}
}
Remember, your array is an object. To change its contents, you just change its contents, you don't have to change the reference to it.
Note, though, that you can use this trick on any modern browser:
function twice() {
this.push.apply(this, this);
}
That works by using the Function#apply function, which calls the function you call it on (so, push in our case) using the first argument you give it as the object to operate on, and the second argument as the arguments to pass into that function (which it takes as an array). More on MDN and in the spec. It happens that push allows you to pass it an arbitrary number of arguments, and will push each one in order. So if you're trying to add the contents of the array to the array a second time, that one line will do it (on modern browsers, some older IE implementations don't like this use of push.apply).
You cannot assign a value to this. That's the rules. But you can modify the value of this. Try pushing some values into this.
function twice() {
var len = this.length;
for (var i = 0; i < len; i++) {
this.push(this[i]);
}
}
Array.prototype.twice = twice;
a = [1, 2, 3];
a.twice();
alert(a);
Here's a fiddle. http://jsfiddle.net/Qvarj/ As you can see, most of the logic is yours.

Javascript: sort multidimensional array

After creating a multi-dim array like this, how do I sort it?
Assuming 'markers' is already defined:
var location = [];
for (var i = 0; i < markers.length; i++) {
location[i] = {};
location[i]["distance"] = "5";
location[i]["name"] = "foo";
location[i]["detail"] = "something";
}
For the above example, I need to sort it by 'distance'.
I've seen other questions on sorting arrays and multi-dim arrays, but none seem to work for this.
location.sort(function(a,b) {
// assuming distance is always a valid integer
return parseInt(a.distance,10) - parseInt(b.distance,10);
});
javascript's array.sort method has an optional parameter, which is a function reference for a custom compare. the return values are >0 meaning b first, 0 meaning a and b are equal, and <0 meaning a first.
Have you tried this?
location.sort(function(a,b) {
return a.distance - b.distance;
});
Both sort functions posted so far should work, but your main problem is going to be using location as a variable as it is already system defined.

Categories