简体   繁体   English

将字符串转换为对象js函数

[英]convert string to object js function

I've been trying to answer the following question but have no idea what step comes next.我一直在尝试回答以下问题,但不知道下一步是什么。 I've tried looking it up but haven't had any luck because most of the answers are in json and I don't know that coding language yet.我试过查找它,但没有任何运气,因为大多数答案都在 json 中,我还不知道这种编码语言。 Below is the question and the code I have so far.以下是我到目前为止的问题和代码。 Thank you.谢谢你。

Create a function named convertStrToObj() that accepts three string parameters.创建一个名为 convertStrToObj() 的函数,它接受三个字符串参数。 All three should be optional parameters.所有三个都应该是可选参数。 If a parameter does not exist set it to 'N/A'.如果参数不存在,请将其设置为“N/A”。 Your function should return an object with three properties first, second, and third.你的函数应该返回一个具有三个属性的对象,第一,第二和第三。 Each of the string parameters should be assigned to that object's properties.每个字符串参数都应分配给该对象的属性。

var object = {
  first: '',
  second: '',
  third: ''
};


function convertStringToObject(string1, string2, string3){
   // do something
}

How do I convert a string into an object using vanilla js?如何使用 vanilla js 将字符串转换为对象?

Am I supposed to use booleans?我应该使用布尔值吗?

Is the object variable redundant?对象变量是多余的吗?

Create an object and assign, checking each parameter.创建一个对象并赋值,检查每个参数。

Your question mentions 'does not exist'.您的问题提到“不存在”。 This is unclear as what to do if it is the NULL value.如果它是NULL值,则不清楚该怎么做。

This example does not enforce that the inputs are strings.此示例不强制输入是字符串。

 function convertStrToObj(a, b, c) { const ret = { first: a === undefined || a === null ? 'N/A' : a, second: b === undefined || a === null ? 'N/A' : b, third: c === undefined || a === null ? 'N/A' : c, } return ret; } console.log(convertStrToObj('foo', 'bar', undefined))

 function convertStringToObject(string1, string2, string3) { return { first: string1 ? string1: 'N/A', second: string2 ? string2: 'N/A', third: string3 ? string3: 'N/A' } } let result = convertStringToObject('a', null, 'c'); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM