开发者

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!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜