-3

1st code:

var str = "Hello";
var arr = str.split("");
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
    text += arr[i] + "<br>"
}
document.write(text);

2nd code: I want to implement the string method split() in the object literal code

var greeting = {
  str: "Hello",
  arr: str.split(""), // string method: split()
  text: " ",
  loop: function() {
      for (var i = 0; i < this.arr.length; i++) {
       this.text += this.arr[i] + "<br>"
       }
      document.write(this.text);
      }
    };
greeting.loop();

So the 2nd code would output the same as the 1st code

lindsey
  • 1
  • 3

1 Answers1

1

The easiest way would be to define arr inside the loop function, like this:

var greeting = {
  str: "Hello",
  text: " ",
  loop: function() {
      var arr = this.str.split("");
      for (var i = 0; i < arr.length; i++) { 
       this.text += arr[i] + "<br>"
       }
      document.write(this.text);
      }
    };
greeting.loop();
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75