用于替换网页中单词的用户脚本

Userscript to replace a word in a webpage

免责声明:我是 JS 菜鸟,我真的一点都不知道,如果这真的是一个菜鸟问题,请原谅。

我发现了一个允许您替换网页上的 words/phrases 的用户脚本。 但是,我有一个错误,指出第 57 行 "expected a conditional expression and instead saw an assignment"

该行是:

for (i = 0; text = texts.snapshotItem(i); i += 1) {

整个脚本:

(function () { 'use strict';
var words = {
    'test 1':'test 2',
    'bleh': 'blah'
};

var regexs = [],
    replacements = [],
    tagsWhitelist = ['PRE', 'BLOCKQUOTE', 'CODE', 'INPUT', 'BUTTON', 'TEXTAREA'],
    rIsRegexp = /^\/(.+)\/([gim]+)?$/,
    word, text, texts, i, userRegexp;

// prepareRegex by JoeSimmons
// used to take a string and ready it for use in new RegExp()
function prepareRegex (string) {
    return string.replace (/([\[\]\^\&$\.\(\)\?\/\\+\{\}\|])/g, '\');
}

// function to decide whether a parent tag will have its text replaced or not
function isTagOk (tag) {
    return tagsWhitelist.indexOf (tag) === -1;
}

delete words['']; // so the user can add each entry ending with a comma,
// I put an extra empty key/value pair in the object.
// so we need to remove it before continuing

// convert the 'words' JSON object to an Array
for (word in words) {
    if (typeof word === 'string' && words.hasOwnProperty (word) ) {
        userRegexp = word.match (rIsRegexp);

        // add the search/needle/query
        if (userRegexp) {
            regexs.push (
                new RegExp (userRegexp[1], 'g')
            );
        }
        else {
            regexs.push (
                new RegExp (prepareRegex (word)
                    .replace (/\?\*/g, function (fullMatch) {
                        return fullMatch === '\*' ? '*' : '[^ ]*';
                    } ),
                    'g'
                )
            );
        }

        // add the replacement
        replacements.push(words[word]);
    }
}

// do the replacement
texts = document.evaluate ('//body//text()[ normalize-space(.) != "" ]', document, null, 6, null);
for (i = 0; text = texts.snapshotItem (i); i += 1) {
    if (isTagOk (text.parentNode.tagName) ) {
        regexs.forEach (function (value, index) {
            text.data = text.data.replace (value, replacements[index]);
        } );
    }
}
} () );

谁能给我解释一下这是什么意思(我喜欢理解我所做的),以及我该如何解决这个问题?

= 是赋值运算符。

赋值在此上下文中无效,因为 for 循环需要一个条件。

您需要使用比较运算符,例如 ==<=>=

一个可能的解决方法是:

for (i = 0; text = texts.snapshotItem(i); i += 1) {

for (i = 0; text == texts.snapshotItem(i); i += 1) {