简体   繁体   中英

javascript: adding strings into an object through a class method

I'm trying to create a javascript class with a couple of methods that would let me add view and delete. I'm stuck with the add method, it should return me a unique ID of each string passed into the add method, but instead I can't figure out how to jump to a next code block when I'm done adding strings. Below is some of my current code:

var obj = {};
var arr = [];

var Words = function(){  
  this.add = function(newWord){
    if(newWord !== false){
      arr.push(newWord); 
    } else {
      for (var i = 0; i < arr.length; i++){        
        obj[i] = arr[i];      
        return obj[i];
      }           
    }

var words = new Words();
words.add('first');
words.add('second');
words.add('third');

I feel I should be creating a next() function of some sort that runs after I'm done pushing the last passed string, but I seem to have forgotten everything.

While I don't really know what you're trying to accomplish, there are some problems with your code...

An Object has keys and values. For every key there is a value.

Ex. mykey: "corresponding value"

for (var i = 0; i < arr.length; i++){        
    obj[i] = arr[i];
    return obj[i];
}

You are setting obj[i] when i is an integer, so unless your keys are integers (probably not), you need to specify keys.

Otherwise, use another array for what you are doing (if possible).

If you are actually filling this object with keys that are numerals, then ignore the above.

I would also point you to using callbacks for finding out when .add() is finished (or just run your code after running .add() ??).


Why not just create an array, set it's values as you want, and retrieve them based on iteration?

var array = [];

//add
array.push("first");

//view value
console.log(array[0]); // output: "first"

//view index
array.indexOf("first"); // output 0

//delete
array.splice(0, 1);

Then wrap this as a class if you'd like:

var array = [];
var Words = function() {
  this.add = function(input) {
    array.push(input);
  }
  this.view = function(input) {
    return array[input];
  }
  this.delete = function(input) {
    array.splice(input, 1);
  }
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM