JavaScript это элемент строки - PullRequest
       2

JavaScript это элемент строки

3 голосов
/ 02 сентября 2010

Глядя на добавление функции обрезки в прототип String, я наткнулся на что-то, что мне кажется странным с помощью строк JavaScript.

if (typeof console === 'undefined') {
    var console = { };
    console.log = function(msg) {
        alert(msg)
    }
}


function isString(str) {
    return ((str && typeof str === 'string') || 
        (str && (str.constructor == String && (str.toString() !== 'null' && str.toString() !== 'undefined'))));
}

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
    };
}
function testing (str) {
    if (isString(str)) {
        console.log("Trimmed: " + str.trim() + " Length: " + str.trim().length);
    } else {
        console.log("Type of: " + typeof str);
    }
    return false;
}

function testSuite() {
    testing(undefined);
    testing(null);
    testing("\t\r\n");
    testing("   90909090");
    testing("lkkljlkjlkj     ");
    testing("    12345       ");
    testing("lkjfsdaljkdfsalkjdfs");
    testing(new String(undefined));                //Why does this create a string with value 'undefined'
    testing(new String(null));                     //Why does this create a string with value 'null'
    testing(new String("\t\r\n"));
    testing(new String("   90909090"));
    testing(new String("lkkljlkjlkj     "));
    testing(new String("    12345       "));
    testing(new String("lkjfsdaljkdfsalkjdfs"));
}

Теперь я знаю, что мы не должны создавать строки с оператором new, но я не хотел бы, чтобы кто-то вызывал это для неопределенной или нулевой строки, которая была создана в следующем виде:

    new String ( someUndefinedOrNullVar );

Чего мне не хватает? Или проверка! == 'null' &&! == 'undefined' действительно необходима (при удалении этой проверки будут отображаться 'null' и 'undefined')?

Ответы [ 3 ]

4 голосов
/ 02 сентября 2010

Из стандарта ECMA :

9.8 ToString
The abstract operation ToString converts its argument to a value of type String according to Table 13 
[ the table shows undefined converts to "undefined" and null to "null"]

... и затем:

15.5.2.1 new String ( [ value ] )
The [[Prototype]] internal property of the newly constructed object is set to the standard built-in String prototype object that is the initial value of String.prototype (15.5.3.1).
The [[Class]] internal property of the newly constructed object is set to "String".
The [[Extensible]] internal property of the newly constructed object is set to true.
The [[PrimitiveValue]] internal property of the newly constructed object is set to ToString(value), or to the empty String if value is not supplied.

Так как ToString(undefined) дает 'undefined', оно делаетчувство.

0 голосов
/ 02 сентября 2010

Все объекты в JavaScript могут быть преобразованы в строковые значения, что и делает new String(null).Проверка !== 'null' && !== 'undefined' в этом случае является предельно надежной, хотя ... следующие все приводят к строке.

'' + null // 'null'
'' + undefined // 'undefined'
[null].join() // 'null'

Но все же имо.дополнительная дурацкая проверка не нужна для trim(), черт, может, у кого-то действительно есть строка 'null' или 'undefined' или, если нет, было бы здорово посмотреть, чтобы вы могли ее отладить.Нет, снимите чек!

0 голосов
/ 02 сентября 2010

Я считаю, что new String (null) и new String (undefined) возвращают типы значений, которые являются строками: 'null' и 'undefined'.

Редактировать: На самом деле, null - это объект.Но я думаю, что я прав насчет неопределенности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...