gpt4 book ai didi

javascript - 面向对象的 Javascript 第 4 章练习 4

转载 作者:行者123 更新时间:2023-11-29 14:53:52 25 4
gpt4 key购买 nike

大家好,我正在通过 Stoyan Stefanov 的书学习 Javascript。我卡在第 4 章练习 4 上:

Imagine the String()constructor didn't exist. Create a constructor function MyString()that acts like String()as closely as possible. You're not allowed to use any built-in string methods or properties, and remember that String()doesn't exist. You can use this code to test your constructor:

>>> var s = new MyString('hello');
>>> s[0];
"h"

我想不出实现“s[0]”的方法,至少以我现在所掌握的知识是这样。

有什么想法吗?

谢谢

最佳答案

对象可以使用类似数组的语法定义自己的属性。可以使用类似数组的语法访问字符串字符。

    function MyString (str) { 

this.length = 0; // string length

var i = 0;
while(str[i] != undefined) {
this.length++;
i++;
}

for (var i=0; i< this.length;i++)
{
this[i]=str[i];
}
}
var s=new MyString('hello');
alert(s[0]); //h

关于javascript - 面向对象的 Javascript 第 4 章练习 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21248583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com