I want to get the index of an array by position. Is this possible? For example, I want the following function to print:
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
printPerson(args);
function printPerson(args) {
for(var i = 0; i < args.count; i++) {
???
}
}
"name:john surname:smith"
(ie name
& surname
should not be hardcoded inside function)
EDIT
The order they printed out is not important!
I want to get the index of an array by position. Is this possible? For example, I want the following function to print:
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
printPerson(args);
function printPerson(args) {
for(var i = 0; i < args.count; i++) {
???
}
}
"name:john surname:smith"
(ie name
& surname
should not be hardcoded inside function)
EDIT
The order they printed out is not important!
- So you just want to print the key / value pairs in an associative array? – Chris Eberle Commented Oct 10, 2011 at 4:54
- 2 You're better off using an object for that. – aziz punjani Commented Oct 10, 2011 at 4:56
- @Chris yes, that's what I'm trying to tell – Caner Commented Oct 10, 2011 at 4:58
6 Answers
Reset to default 4You are assigning properties to an Array, and want those properties to appear in some order?
No need for an Array. Better use an Object literal:
var person = {
name:'John',
surname:'smith',
toString: function(){
return 'name: '+this.name
+', surname: '+this.surname;
}
};
alert(person); //=>name: john, surname: smith
Not tested:
for(var i in args)
alert(i + ":" + args[i]);
EDIT:
If order matters, you could make an array of objects.. Like
args[0] = { key: 'name', value: 'john' };
args[1] = { key: 'name', value: 'mike' };
for(var i = 0; i < args.length; i++)
alert(args[i].key + ":" + args[i].value);
Or something..
These values are simply properties of the args
object. So you can iterate over them by using for...in
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
for(x in args)
document.write(x + ":" + args[x] + " ");
<html>
<body>
<script type="text/javascript">
var args = new Array();
args["name"] = "john";
args["surname"] = "smith";
function printPerson(args) {
for(key in args) {
alert(key + ":" + args[key]); // you can write your values, rather than alert them, but gives you the idea!
}
}
printPerson(args);
</script>
</body>
</html>
This isn't the correct use of Array
in JavaScript, which should only use a numeric index. By adding string-key properties, you are adding instance properties but they aren't enumerable in a for
loop. You can use an Object
instead, which is a set of key/value pairs.
KooiInc's answer demonstrates the use of Object
for this purpose.
I think you can use for .. in for this. There's an example on that page.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745292275a4620932.html
评论列表(0条)