去除前导和尾随空格

4

去掉名称“undefined”中的前导和尾随空格。

trimName接受一个人作为参数。Person将始终是一个对象。如果未定义名称,则返回undefined。否则,返回修剪后的名称。

var person = {};
var trimmedName;
person.name;
function trimName(person) {
  // If you do not set this variable to a value, it will be
  // undefined.
  // Do a check here to see if a person's name is defined.
  if (person.name = 'undefined') {
    return 'undefined';
  }
  else {
    trimmedName = person.name.trim();
    return trimmedName;
  }
}
trimName(' sam ');

你想返回 undefined 还是 'undefined' (字符串)? - kapa
3
请注意,String.prototype.trim 在某些浏览器中不可用(特别是 IE9 及以下版本),因此您需要使用一个 shim(或者,如您所标记的 jQuery)jQuery.trim。目的是使内容更加通俗易懂,不改变原意。 - James Allardice
3个回答

3

我在这里看不到问题,但是代码存在以下问题:

  • 您在应该使用比较运算符==的地方使用了赋值运算符=
  • 将字符串与字符串'undefined'进行比较并不是检查属性是否为未定义的方法。
  • trim方法只存在于最新版本(9)的IE中。
  • 您正在使用字符串而不是对象调用函数。

代码:

function trimName(person) {
  var trimmed;
  if (typeof person.name == 'undefined') {
    trimmed = 'undefined';
  } else {
    trimmed = person.name.replace(/(^\s+|\s+$)/g, '');
  }
  return trimmed;
}

var trimmedName = trimName({ name: ' sam ' });

Demo: http://jsfiddle.net/Guffa/vCkSq/


2

您应该做的是:

var personTest = {name: '  sam'};

function trimName(person) {
  // If you do not set this variable to a value, it will be
  // undefined.
  // Do a check here to see if a person's name is defined.
  if (typeof person.name === 'undefined') {
    return 'undefined';
  }
  else {
    var trimmedName = person.name.trim();
    return trimmedName;
  }
}
alert(trimName(' sam '));
alert(trimName(personTest));

pastebin http://jsbin.com/oqovog/edit#source


在函数内部放置 var trimmedName; 会更好。 - kapa

0
function trimName(person) {
  // Check if the name of the person was defined
  // If not, return undefined
  if (person.name == 'undefined') {
    return 'undefined';
  }
  else {
    // Otherwise trim the name and return it.
    return person.name.replace(/^\s+|\s+$/g, '');
  }
}

// Create a person, set his name to " sam " with the spaces.
var person = {};
person.name = " sam ";

// Pass sam (the person object) to your function
// Then alert() the result.
alert(trimName(person));

看一下这里的代码并阅读注释。我们创建一个人物对象,用前导和尾随空格设置他的名字。我们将它传递给函数,在那里我们测试它是否被定义。如果是,我们返回修剪后的名称。

以下已编辑。

var person = {}; //creates the object "person"
person.name = prompt('Please enter a name'); //defines name as a property
function trimName(person) { //and gives it a value
// If the property "name" is undefined
// return undefined
if (name === undefined) { //returns the code state "undefined"
  return undefined; // if name is undefined
} else if (person.name === '') { //returns a prompt if no name is entered
  return 'Please enter a name';
} else {
// Trim the "name" property, ensure it is a string
return (person.name + '').trim(); //trims leading/trailing spaces
}
}
trimName(person); //defines object person as a variable of function trimName

这不是检查 undefined 的正确方式。https://dev59.com/InA75IYBdhLWcg3wRWsU - kapa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接