I declare an array globally:
var array = new Array;
I declare constructor for Element
function Element(type, format ) {
this.type= type;
this.format = format;
this.returnElement = function() { return this.element; }
}
I want to return the value of one of parameters while it's in the array:
function analyse()
{
for(var i=0, len=array.length; i < len; i++)
{
var a = array[i];
var b = a.type;
alert(b);
}
}
}
Now, I want to return the value of the object's property at i.
No idea what you exactly want, but there are several mistakes:
Element is no object, but a constructor function (which is of course a Function object, yes)
array.slice(0) empties the array and returns a new array with all the elements from index 0 up
var a = becomes that new array, and is not an Element object. An array has no property "type"
You might want to do
for (var i=0, len=array.length; i < len; i++) {
var a = array[0];
//console.assert(a instanceof Element, "wrong array component detected");
var b = a.type;
}
ok, resolved, it was trivial and i'm dumb. just added these lines of code:
var element = new Element();
element = array[i];
and it worked...
Related
I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.
When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.
var array = [];
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}
However, when I call the value held in that property (i.e.):
console.log(array[2].someFunction)
It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.
Basically you had some problems in your code, like:
not defining number
using var instead of let
not defining the object
using the same value as parameter of the function
here you have the working solution.
var array = [];
// numbers was not defined.
const number = 10;
// use let instead of var
for (let i = 0; i < number; i++) {
// you are not instantiating your object, here is an example.
array[i] = {
"foo": "bar",
"index": i,
}
// you have to change i to j, because if you use i
// it will be the parameter of the function
array[i].someFunction = function(j) {
console.log('index: ', i);
console.log('parameter: ', j)
}
}
// we see the function
console.log(array[2].someFunction)
// we call the function succesfully
array[2].someFunction(100);
It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:
var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
array[i].index = i;
array[i].someFunction = function(){console.log(this.index);}
}
//and see that it's working...
for(var i = 0; i < array.length; i++){
array[i].someFunction();
}
When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}
You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']
You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}
I have a function that simply returns the longest property of a given array.
It's a for loop that assigns the looped property to a variable, with the length of the property is longer than that of the variable.
And at last it returns this new variable. But I get an error in line 10, that it can't read the length of undefined.
It seems to have a problem with someArray[i].length inside the for loop.
function longestString(i) {
// i will be an array.
// return the longest string in the array
var someArray = i;
console.log(someArray);
var longestItem = someArray[0];
console.log(longestItem);
for (i = 0; someArray.length; i++) {
if (longestItem.length < someArray[i].length) {
console.log(longestItem);
console.log(someArray[i]);
longestItem = someArray[i];
}
}
document.write(longestItem);
console.log(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
Any suggestions?
Your for-loop's condition has error.
It should be like given below.
for (i = 0; i < someArray.length; i++)
Check out this fiddle.
Here is the complete code.
function longestString(i) {
// i will be an array.
// return the longest string in the array
var someArray = i;
document.write(someArray); // just testing
var longestItem = someArray[0];
for (i = 0; i < someArray.length; i++) { //Changes in the condition
if (longestItem.length < someArray[i].length) {
longestItem = someArray[i];
}
}
document.write(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
First of all don't use the same name ifor the function parameter and then in the for loop counter, you may put yourself in really big troubles.
Second thing, your loop doesn't have a stop condition you missed i<someArray.length, it should be like this:
for (i = 0; i<someArray.length; i++) {
if (longestItem.length < someArray[i].length) {
console.log(longestItem);
console.log(someArray[i]);
longestItem = someArray[i];
}
}
Last thing use console.log() or console.dir() to debug/test instead of document.write() because it's a very very bad practice.
There are two errors on your for loop:
You are using an i function parameter which you are using again in your for loop. Try to use a different variable name inside your for loop or at least define the variable with var (to retain the scope), otherwise you will shadow the variable declared as function parameter.
The second one is that you forget to include the test condition into the loop.
function longestString(len) {
// i will be an array.
// return the longest string in the array
var someArray = len;
var longestItem = someArray[0];
var length = someArray.length;
for (var i = 0 ; i < length; i++) {
if (longestItem.length < someArray[i].length) {
longestItem = someArray[i];
}
}
console.log(longestItem);
return longestItem;
}
longestString(['a', 'ab', 'abc']) // should return 'abc'
Maybe there's more than one longest string. I'd suggest looking at the Array instance iteration methods.
var array = ['a', 'abc', 'ab', 'def'];
var maxlen = Math.max.apply(null, array.map(function(string){
return string.length;
}));
var longest = array.filter(function(string){
return string.length === maxlen;
});
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(longest);
document.body.appendChild(pre);
charFreq function that's not quite working out. Hit a wall. I know I may need to
do a conditional. Calling the function returns an Object error. I'm attempting
to get string into an empty object displaying the characters like this - Object
{o: 4, p: 5, z: 2, w: 4, y: 1…}. New to Javascript by the way.
Just realized I shouldn't be appending anything. Do I need to do a .push() to
push the array into the object?
function charFreq (string){
var emptyObj = {};
for(var i = 0; i < string.length; i++) {
// console.log(string.charAt(i));
var args = [string.charAt(i)];
var emptyArr = [''].concat(args);
emptyObj += emptyArr
}
return emptyObj
}
undefined
charFreq('alkdjflkajdsf')
"[object Object],a,l,k,d,j,f,l,k,a,j,d,s,f"
You just need to set emptyObj's key of that specific letter to either 1 if it doesn't exist or increment the count if it already does.
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
if (!obj.hasOwnProperty(string[i])) {
obj[string[i]] = 1;
} else {
obj[string[i]]++;
}
}
return obj;
}
console.log(charFreq('alkdjflkajdsf'));
Try this instead: you need to create an object property first, then increment it. What you do, is implicitly convert the object to a string and concatenate more string data to it (using += and concat).
This is a simple approach:
function charFreq(string){
var emptyObj={};
for(var i=0; i<string.length; i++) {
if(!emptyObj.hasOwnProperty(string[i])){ // if property doesn’t exist
emptyObj[string[i]]=0; // create it and set to 0
}
emptyObj[string[i]]++; // increment it
}
return emptyObj;
}
A modified version of Richard Kho's code:
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
var c=string[i];
if (c=='') continue;
if (obj[c]==null) obj[c]=0;
obj[c]++;
}
return obj;
}
I'm trying to implement a duplicate method to the js Array prototype which concats a duplicate of the array to itself like so:
[11,22,3,34,5,26,7,8,9].duplicate(); // [11,22,3,34,5,26,7,8,9,11,22,3,34,5,26,7,8,9]
Here's what I have, but it causes the browser to crash:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var j = this.length;
for(var i = 0; i < this.length; i++) {
this[j] = this[i];
j++;
}
return this;
}
I'm trying to do this using native JS as practice for iterations and algorithms so I'm trying to avoid built-in methods, if possible, so that I can get a clearer understanding of how things are being moved around.
Any ideas on why it is crashing and how I can optimize it?
The code inside the loop changes the length of the array, so it will just keep growing and you will never reach the end of it. Get the initial length of the array in a variable and use in the loop condition. You can use that as offset for the target index also instead of another counter:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var len = this.length;
for (var i = 0; i < len; i++) {
this[len + i] = this[i];
}
return this;
}
The length of the array is increasing with each element added so you can not use this as a terminator. Try this.
var j = this.length;
for(var i = 0; i < j; i++) {
this[i+j] = this[i];
}
Here's simplest code
Array.prototype.duplicate = function () {
var array = this;
return array.concat(array);
};
Using Spread syntax;
In a method, this refers to the owner object.
Array.prototype.duplicate = function () {
return [...this, ...this]
};
let array = [1,2,3,4,5];
Array.prototype.duplicate = function () {
return [...this, ...this]
};
console.log(array.duplicate());