I am having trouble calling an arguement in the functin below.
function makeScales(size,note1,note2,note3,note4,note5,note6,note7,note8){
for(var z=0; z<size; z++){
if(semis=="Sharps"){
notes = notes + " - " + noteSharp["note" + z];
} else {
notes = notes + " - " + noteFlat["note" + z];
}
}
}
I went through many debugging procedures and found that my error en-lies with noteSharp["note" + z] more specifically "note" + z . For example if i do console.log(noteSharp[note1]) i get the desired result and i set z to 7 so i can see that its populating appropriately but I get undefined for my results. Any help would be greatly appreciated.
"note" + z
will give you a string like "note1"
not an identifier.
If you want to access a piece of data by an index, then put it in an array, not in a variable with a number in its name.
For example:
function makeScales(size, notes) {
//...
notes = notes + " = " + noteSharp[ notes[z] ];
//...
}
makeScales( "some size", [ "foo", "bar", "baz" ] );
Alternatively (and I wouldn't recommend this approach as it mixes different kinds of data in a single data structure), you can use the arguments
object.
notes = notes + " - " + arguments[z];
arguments
represents all the arguments passed to the function. The second argument (aka note1
) will have the index 1
and so on.
Your problem there is that noteSharp[note1]
is using the value of the variable note1
as the key to lookup, whereas noteSharp["note" + z]
results in a string of "note"
followed by the value of z
.
To reference a variable name via a string, use eval
:
noteSharp[eval("note" + z)];
However, I would highly recommend not using eval
. Others do too , but perhaps there is a counterpoint .
Pass note1
, note2
, ..., noteN
as properties of an object. Therefore you can look up their values exactly as you desire, just one level deeper.
function makeScales(size, notes) {
var z = 1;
var note1 = notes["note" + z];
}
// Calling makeScales with our notes.
makeScales(10, {
note1: 'c',
note2: 'd',
note3: 'e',
// etc.
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.