Javascript我如何编辑和更新对象

问题描述 投票:0回答:1

JavaScript新手!如果要编辑和更新具有预先存在的值的对象怎么办?

array [];

// this function is for pre-existed value
function object1 ( mytext ) {
this.text = mytext
}

var usertext = new object ("my text to edit");
memArray.push (usertext);
console.log (usertext)

关于提示值的编辑/更新呢?

function object2(){
   var text
   this.getData = function(){
       return{
       text:  this.text
}
}
   this.setData = function (){
       this.text = prompt ("Type anything");
}
   return this.setData();
}
   var user = new addUserObject;
       memArray.push(user.getData());
       console.log(memArray);
arrays object prompt
1个回答
0
投票

[有很多方法,但是我的方法是对要编辑和更改的单词使用“ for”迭代。

var myArray = ["hello" , "hi"];
console.log(myArray);

function addToArray(str){
  myArray.push(str);
}
addToArray("yo");
console.log(myArray);

function editArray(){
  var word = prompt("Please enter which word you want to change:", "");
  if (word != null && word.length > 0){
    var found = false;
    for (var i = 0; i < myArray.length; i++){
      if (word == myArray[i]){
        found = true;
        var editWord = prompt("You want to change \"" + word + "\" to:", "");
        if (editWord != null && editWord.length > 0){
          myArray[i] = editWord;
        } else {
          console.log("You input nothing.");
        }
        break;
      }
    }
    if (!found){
      console.log("Cannot find this word");
    }
  } else {
    console.log("You input nothing.");
  }

}
editArray();
console.log(myArray);
© www.soinside.com 2019 - 2024. All rights reserved.