![](/img/trans.png)
[英]how can I get the name of each argument in the arguments object in javascript
[英]How can I get the name of the key from object arguments in javascript
可以說我有一個如下所示的函數:
function foo()
{
console.log(arguments);
}
foo(event_1="1", event_2="2");
在這種情況下,輸出將是:
[object Arguments] {
0: "1",
1: "2"
}
如何獲取參數(event_1,event_2)而不是(0,1)的鍵?
與@Robby的答案類似,您也可以使用Object.keys
:
function foo() {
console.log(Object.keys(arguments[0]));
}
foo({event_1:"1", event_2: "2"});
將參數作為對象傳遞,並遍歷對象的屬性名稱:
function foo() {
for (var key in arguments[0]) {
console.log(key);
}
}
foo({event_1: "1", event_2: "2"});
在這種情況下,0和1確實是參數的鍵。 使用event_1="1"
您不是將鍵傳遞給函數,而是將值"1"
分配給變量event_1
,然后將值傳遞給函數。
如果您需要傳遞鍵/值對,則可以使用對象:
function foo(data)
{
for (var key in data)
{
console.dir("key="+key+", value="+data[key]);
}
}
foo({ first: "hello", second: "bye" });
我不知道這是否對您有幫助,但是您可以使用一個對象。 像這樣:
function foo(anobj)
{
console.log(anobj.event_1, anobj.event_2);
}
foo({event_1:"1", event_2:"2"});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.