当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Get the index of an array by position

问题描述:

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!

网友答案:

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..

网友答案:

You 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
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: