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));
Посмотрите код здесь и прочитайте комментарии.Мы создаем объект человека, устанавливаем его имя с пробелом в начале и в конце.Мы передаем его функции, в которой мы проверяем, определено ли оно.Если это так, мы возвращаем обрезанное имя.
Следующее редактируется.