javascript 对象设置器只存储字符串的第一个字符[已关闭]

z9ju0rcb  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(91)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由一个错字或一个无法再复制的问题引起的。虽然类似的问题可能是on-topic在这里,但这个问题的解决方式不太可能帮助未来的读者。
1小时前关闭
Improve this question
我已经设置了一个对象集来存储用户在单击按钮时在表单中输入的数字和文本。但是JS setter只存储对象中每个字符串/整数的第一个字符。
如果setter使用GetElementbyID获取数据,或者使用也从GetElementbyID获取数据的变量,就会发生这种情况。
是否有解决方法?this similar question中的回复不适用。
此代码的目的是从用户输入的数据创建一个临时对象,该对象将被克隆到本地存储中的另一个对象。
下面的示例代码。完整的测试代码在CodePen. 2
我是一个初学Javascript的人。
谢谢。

<!-- user will be entering text and numbers -->
 
<label for="charname" class="right-align"><span class="side-menu-item-label" style="font-weight: 700;">Name</span></label><input class="number-entry" id="charname" type="text" maxlength="10" size="12" value="Joe" placeholder="Joe">

<label for="strength" class="right-align"><span class="side-menu-item-label" style="font-weight: 700;">Strength</span></label><input class="number-entry" id="strength" type="number" maxlength="2" min="1" max="99" value="12" placeholder="12">

<!-- button to call saveStats func --> 

<button type="submit" class="roll clickHandler shadow" name="savestats" value="" id="savestats" title="Save stats" onclick="StatsSave()"><label class="roll" for="savestats">Save stats</label></button>
// JS setters 

const SavedCharacters = {};

var charname;
var statStr;

function StatsSave() {
  // store user data in variables

  var charname = document.getElementById("charname").value;
  var statStr = document.getElementById("strength").value;

  // JSON setters
  // "let" is used instead of "const", as the "character" object is to be nested in "SavedCharacters", which will put in local storage.

  let character = {
    Name: "valueCharname",
    set setName(valueCharname) {
      [this.Name] = charname;
    },

    Strength: "valueStrength",
    set setStrength(valueStrength) {
      [this.Strength] = statStr;
    },
  };

  character.setName = document.getElementById("charname").value;
  character.setStrength = document.getElementById("strength").value;

}
oyxsuwqo

oyxsuwqo1#

根据motto的注解,我将JS行[this.Name] = charname更改为this.Name = valueCharname,整个字符串存储在JSON对象中。

// JSON setters
  // "let" is used instead of "const", as the "character" object is to be nested in "SavedCharacters", which will put in local storage.

  let character = {
    Name: "valueCharname",
    set setName(valueCharname) {
      this.Name = valueCharname;
    },

    Strength: "valueStrength",
    set setStrength(valueStrength) {
      this.Strength = valueStrength;
    },
  };

相关问题