簡體   English   中英

用戶輸入對象的屬性和鍵的方法

[英]How to user-input an object property and key

我手里有一個非常罕見的問題。 我需要用戶輸入對象的鍵和屬性。

我有一個input

<input type="text">
<input type="button" value="enter">

我的js:
接受輸入的文本,並將其存儲在var input
例如,如果用戶輸入“ hello”,則...

var myObj = {
  hello: "hello"
}

有沒有辦法做到這一點?
謝謝

像這樣嗎

https://jsfiddle.net/mjjLxqnr/3/

HTML:

<input type="text" id="yourInput">
<input type="button" value="Enter" id="enterBtn">

JavaScript的:

var obj = {},
    enterBtn = document.getElementById('enterBtn'),
    yourInput = document.getElementById('yourInput');

enterBtn.onclick = function () {
    var input = yourInput.value;
    // Don't add anything to the obj if the input is empty.
    if(!input) return;
    // Use brackets to add a property to the obj, and set the value to be the same
    // as the property name.
    obj[input] = input;
    console.log(obj);
};

您需要使用方括號表示法:

如果將輸入存儲在名為input的變量中,則可以執行以下操作:

var myObj = {};
obj[input] = input;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM