How to verify containing values in hash tables without loop in javascript?
For example:
var a = new Object(); // or just []
a[0] = 0
a['one'] = 1;
a['two'] = 2;
a['three'] = 3;
You can use hasOwnProperty
var hash = new Object(); // or just {}
hash['one'] = 1;
hash['two'] = 2;
hash['three'] = 3;
if (hash.hasOwnProperty(k)) {
alert('Has')
}
Try jQuery
$(hashtablename).each(function (item) {
//code to verify.
});
although internally it will prob still use a loop..
Related
Wondering if it is possible to use a loop to add dynamically named objects to an array, so I don't need to repeat the "push" on an array. Tks !!
let _objA0 = { "name":"regionId", "value":"myRegion" };
let _objA1 = { "name":"vdcId", "value":"myId" };
let _objA2 ... _objA100
let test = []
test.push(_objA0)
test.push(_objA1)
...
test.push(_objA100)
I guess it's the right time to use eval
let test = [];
for(let i = 0; i <= 100; i++) {
test.push(eval(`_objA${i}`));
}
You can access variables (with var keyword) by window object , try this:
var _objA0 = { "name":"regionId", "value":"myRegion" };
var _objA1 = { "name":"vdcId", "value":"myId" };
let test = [];
for(let i = 0; i < 2; i++){
test.push(window['_objA' + i]);
}
console.log(test)
Consider the following code:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var globalList = Array();
globalList[0] = "Test";
globalList[1] = "Another Test";
async function coreFunc(promiseName, sleepTime) {
console.log("Started CoreFunc: "+promiseName);
var localList = globalList;
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
if (promiseName != "Promise0") {
for (i = 0; i < localList.length; i++) {
console.log(localList[i]);
}
}
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
await sleep(sleepTime);
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
console.log("Done with CoreFunc: "+promiseName);
}
async function testMultiplePromises() {
var thArray = Array();
for (i = 0; i < 4; i++) {
var pr = new Promise(resolve => coreFunc("Promise" + i, 3000));
thArray[i] = pr;
}
for (i = 0; i < thArray.length; i++) {
await thArray[i];
}
}
globalList is an array that is global. When the above code is invoked like the following:
await testMultiplePromises();
The code goes into an infinite loop. The problem is definitely in the following segment where I am reinitializing the global variable to some different array:
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
Is there a way to copy the global datastructure to a local variable without leading to index out of bounds or infinite loop kind of issues? The following code is definitely not doing the job:
var localList = globalList;
What should be done in order to ensure that the Promises either get the older array or get the newer array? To rephrase, how do I make sure the code inside coreFunc (Promise0) that changes the global data structure is protected?
Infinite loop is caused by global i variable on for loops. You should type it like this
...
for (var i = 0; i < localList.length; i++) {
...
for (var i = 0; i < 4; i++) {
...
for (var i = 0; i < thArray.length; i++) {
...
To "protect" array you can just copy it like this
var localList = JSON.parse(JSON.stringify(globalList));
There are a few problems in your code.
var globalList = Array(); - missing the new keyword here.
var localList = globalList; - this does NOT create a copy of the Array, it just creates a reference to the outer array. So whatever you change in localList will also be changed in globalList. Try this: var localList = [...globalList];. This creates a (shallow) copy.
globalList = testList; - same here.
A good read about pass by value vs. pass by reference can be found here.
I currently have an object that adds itself to an array whenever a new one is created. Eventually, I want to remove all of the references in the array so I can add new ones.
I've created an object method (this.removeFromArray()) that looks for itself in the array and splices itself out. removeAll() runs a for loop that makes each object in the array run removeFromArray(), so I expect that when I try to read out the items in the array, I should get nothing.
Instead, depending on the amount of objects created, I get one or two left behind. How can I fix this and have all objects in the array cleared out?
var objArray = [];
function obj(name) {
objArray.push(this);
console.log("Created "+name);
this.name = name;
this.removeFromArray = function() {
objArray.splice(
objArray.findIndex(function(e) {
return e == this;
}),
1
);
}
}
function removeAll() {
for (var i = 0; i <= objArray.length - 1; i++) {
objArray[i].removeFromArray();
}
}
var foo = new obj("foo");
var bar = new obj("bar");
var cat = new obj("cat");
var dog = new obj("dog");
var bird = new obj("bird");
removeAll();
for (var i = 0; i <= objArray.length-1; i++) { //Check the values in the array for leftovers
console.log(objArray[i].name);
}
//Expected nothing in the console but the creation messages, got foo and bar instead
If you want to simply delete all the created object, edit removeAll() function like below:
Note that you have to create a variable for objArray.length, not directly put the objArray.length to for() loop.
function removeAll() {
var len = objArray.length;
for (var i = 0; i <= len - 1; i++) {
objArray.splice(0,1);
}
}
better way to achieve this would be to utilize inheritance through prototype. it is better than creating a function inside the constructor object.
var objArray = [];
function Obj(name) {
this.name = name;
objArray.push(this);
}
Obj.prototype.removeFromArray = function() {
var i = -1,
len = objArray.length,
removed = null;
while (++i < len) {
if (objArray[i] === this) {
removed = objArray.splice(i, 1);
removed = null; //nullify to free memory, though not that necessary
break;
}
}
};
Obj.prototype.removeAll = function() {
var len = objArray.length,
removed = null;
//note that i started from the last item to remove to avoid index out of range error
while (--len >= 0) {
removed = objArray.splice(len, 1);
removed = null; //nullify to free memory, though not that necessary
}
};
I am using for loop in javascript and store value in multiple variables.
var friend_id1 = '';
var friend_id2 = '';
var friend_id3 = '';
FB.api('/me/friends', function(response) {
if(response.data) {
obj = response.data
obj = shuffle(obj);
a = 3;
for(x = 1; x <= obj.length; x++){
friend_id[x] = obj[x].id;
if(x >= a) break;
}
} else {
alert("Error!");
}
});
if i replace friend_id[x] to friend_id1 i will get user id. But i want store values in multiple variables.
You're trying to save the values to an array:
friend_id[x] = obj[x].id;
But you didn't declare an array, you have no array variable called friend_id. Instead, you have multiple variables with numbered names.
Just declare the array as you want to use it:
var friend_id = [];
Or, more aptly named:
var friend_ids = [];
And more properly used:
friend_ids.push(obj[x].id);
I want to generate samples with lodash and it return me the same numbers for each line. what im doing wrong?
var primaryNumsCells = _.range(50);
var extraNumsCells = _.range(20);
var lottery = {lineConfigurations: []};
var numsConfig = {lineNumbers: {}};
for( var i = 0; i < 2; i ++ ) {
numsConfig.lineNumbers.primaryNumbers = _.sample(primaryNumsCells, 5);
numsConfig.lineNumbers.secondaryNumbers = _.sample(extraNumsCells, 2);
lottery.lineConfigurations.push(numsConfig);
}
console.log(lottery);
The results of the first object and second object of the primary and secondary numbers is the same;
here is the fiddle:
http://jsbin.com/vavuhunupi/1/edit
Create a new object inside a loop. It's easy to do with a plain object literal (dropping the variable):
var lottery = {lineConfigurations: []};
for (var i = 0; i < 2; i++) {
lottery.lineConfigurations.push({
lineNumbers: {
primaryNumbers: _.sample(primaryNumsCells, 5),
secondaryNumbers: _.sample(extraNumsCells, 2)
}
});
}
As it stands, at each step of the loop you modify and push the same object (stored in numsConfig var).
And here goes a lodash way of doing the same thing:
var lottery = {
lineConfigurations: _.map(_.range(2), function() {
return {
lineNumbers: {
primaryNumbers: _.sample(primaryNumsCells, 5),
secondaryNumbers: _.sample(extraNumsCells, 2)
}
};
})
};