如何使用函数编辑字符串数据?

问题描述 投票:0回答:2

注意:这是一个旧问题,用于引用 GitHub 页面。该页面已被删除,因此此问题已更新以删除链接。

我正在尝试在我的聊天室中创建一个系统,如果您在聊天中输入某个单词(密码),它将编辑用户名以包含特殊的 mod 标签。我这样做是因为我们没有配置文件系统,这是我能想到的最佳解决方案。但是我遇到了一个问题,我不知道如何编辑字符串的数据(在本例中为用户名)以使用函数向其添加内容。如果有人可以提供帮助,将不胜感激。

代码:

if(data.message = password) {
  username.data + "Mod" 
}

额外的问题:在上面的例子中,如果(data.message=password)让它包含变量(密码),它就会改变它,或者如果他们输入“密码”,它就会改变它改变它?

javascript variables editing
2个回答
0
投票

您需要将新值赋回变量,如下所示:

if(data.message == password) {
  username.data = username.data + "Mod";
  // or using template string
  username.data = `${username.data}Mod`;
}

我假设用户名是一个 JSON 对象。

补充回答: 在

==
条件下,需要使用
===
(仅值)或
if
(严格检查数据类型和值)。如果
data.message
正是密码的值,则满足条件。

如果你想检查密码是否是子字符串(消息中包含消息中任何位置的密码值),那么你需要使用String.prototype.includes。演示如下:

if(data.message.includes(password)) {
  username.data = username.data + "Mod";
  // or using template string
  username.data = `${username.data}Mod`;
}

如果还有更多疑问,可以在下方评论。我会更新这个答案。

编辑:

阅读您的评论后,我添加以下示例以向您展示上述代码的工作原理:

/*
Author: chankruze ([email protected])
Created: Mon Jan 31 2022 12:46:44 GMT+0530 (India Standard Time)

Copyright (c) geekofia 2022 and beyond
*/

const password = "qwerty1234"

const data = {
    message1: `this is my ${password}`,
    message2: password,
}


const username = {
    data: "chankruze",
}

console.log(username.data);

if (data.message1.includes(password)) {
    console.log("password found in side data");

    username.data += "mod";
}

console.log(username.data);

if (data.message2 === password) {
    console.log("exact match");

    username.data = `${username.data}mod`;
}

console.log(username.data);

0
投票
  • 单个
    =
    表示赋值,
    ==
    ===
    是相等比较(查找差异)
  • 要附加到字符串末尾,请执行
    +=
  • 为了回答你的最后一个问题,
    == password
    的意思是“如果
    data.message
    完全等于变量
    password
    的值,则为真”。如果您想查看变量
    password
    是否包含在字符串中,请执行
    data.message.contains(password)
const checkForMod = (data, username) => {
  if (data.message == password) {
    username.data += "Mod";
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.